import { getUserInfo } from "@/api/user";

// 用户信息泛型
export type UserInfo= {
  user_id?: number;
  account?: string;
  id?: number;
  name?: string;
  pic?: string;
  pwd?: string;
  create_time?: string;
  update_time?: string;
  avatar?: string;
}

/**定义用户信息操作类 */
export default class User {
  private constructor() {}

  /**不让外部实例化 */
  private static _instance: User;

  public static get instance(): User {
    return this.getInstance();
  }

  /**单例模式 */
  private static getInstance(): User {
    if (!this._instance) {
      this._instance = new User();
    }
    return this._instance;
  }

  /**从localstore获取用户信息*/
  public getUserInfo(): UserInfo | null {
    const userInfo = localStorage.getItem("user-info");
    if (userInfo) {
      return JSON.parse(userInfo);
    } else {
      return null;
    }
  }

  /**保存用户信息到localstore*/
  public saveUserInfo(userInfo: UserInfo) {
    localStorage.setItem("user-info", JSON.stringify(userInfo));
  }

  /**清除用户信息*/
  public clearUserInfo() {
    localStorage.removeItem("user-info");
  }

  /**获取用户信息 */
  public getUserInfoById(): void {
    const userInfo = this.getUserInfo();
    if (userInfo) {
      getUserInfo({id: userInfo.id}).then((res) => {
        this.saveUserInfo(res.data)
      });
    }
  }
}
